/**
 * Created by Multi on 2019/4/6.
 */

 var appData = {
  getData:function(count){
      var countries = 'US,Germany,UK,Japan,Italy,Greece'.split(','),
          data = new wijmo.collections.ObservableArray();

      for(var i=0;i<count;i++)
      {
          data.push({
              id:i,
              country:countries[i%countries.length],
              date:new Date(2014,i%12,i%28),
              amount:Math.random() * 10000,
              active:i%4 == 0
          });
      }
      return data;
  }
};

// first grid for flexgrid
var grid = new wijmo.grid.FlexGrid("#gsFlexGrid");
grid.itemsSource = appData.getData(50);

var fgInitMethod = new wijmo.grid.FlexGrid('#cdInitMethod'),
  fgColsCollection = new wijmo.grid.FlexGrid('#cdColsCollection'),
  cv = new wijmo.collections.CollectionView(appData.getData(100));

fgInitMethod.initialize({
  isReadOnly:true,
  autoGenerateColumns:false,
  columns:[
      {header:'Country',binding:'country',width:'*'},
      {header:'Date',binding:'date'},
      {header:'Revenue',binding:'amount',format:'n2'},
      {header:'Active',binding:'active'},
  ],
  itemsSource:cv
});


// initialize the other grid using the columns collection.
fgColsCollection.autoGenerateColumns = false;
fgColsCollection.itemsSource = cv;
var c = new wijmo.grid.Column();
c.binding = 'country';
c.header = 'Country';
c.width = '*';
fgColsCollection.columns.push(c);

c = new wijmo.grid.Column();
c.binding = 'date';
c.header = 'Date';
fgColsCollection.columns.push(c);

c = new wijmo.grid.Column();
c.binding = 'amount';
c.header = 'Revenue';
fgColsCollection.columns.push(c);

c = new wijmo.grid.Column();
c.binding = 'active';
c.header = 'Active';
fgColsCollection.columns.push(c);


// selection module for flexGrid
// initialize grid and menu
var grid = new wijmo.grid.FlexGrid('#smFlexGrid'),
  menu = new wijmo.input.Menu('#smMenu'),
  cv = new wijmo.collections.CollectionView(appData.getData(100));

grid.itemsSource = cv;
updateMenuHeader();

menu.itemClicked.addHandler(function(sender){
  grid.selectionMode = sender.selectedValue;
  updateMenuHeader()
});

function updateMenuHeader(){
  menu.header = '<b>selection Mode:</b>'+menu.text;
}

// group for flexGrid
// initialize grid and menu
var ggrid = new wijmo.grid.FlexGrid('#gFlexGrid'),
  gMenu = new wijmo.input.Menu('#gMenu'),
  cv = new wijmo.collections.CollectionView(appData.getData(100));

ggrid.initialize({
  autoGenerateColumns:false,
  columns:[
      { header: 'Country', binding: 'country', width: 220 },
      { header: 'Date', binding: 'date',format:'MMM-dd-yyyy' },
      { header: 'Revenue', binding: 'amount', format: 'n0' ,width:90}
  ],
  itemsSource:cv
});
updateGMenuHeader();

gMenu.itemClicked.addHandler(function(sender){
  var groupBy = sender.selectedValue;
  cv.groupDescriptions.clear();
  if(groupBy)
  {
      var groupNames = groupBy.split(',');
      for(var i=0;i<groupNames.length;i++)
      {
          var groupName = groupNames[i];
          if(groupName == 'date')
          {
              var groupDesc = new wijmo.collections.PropertyGroupDescription(groupName,function(item,prop){
                  return item.date.getFullYear();
              });
              cv.groupDescriptions.push(groupDesc);
          }else if(groupName == 'amount')
          {
              var groupDesc = new wijmo.collections.PropertyGroupDescription(groupName,function(item,prop){
                  return item.amount >= 5000?'> 5,000':item.amount >= 500?'500 to 5,000':'<500';
              });
              cv.groupDescriptions.push(groupDesc);
          }else{
              var groupDesc = new wijmo.collections.PropertyGroupDescription(groupName);
              cv.groupDescriptions.push(groupDesc);
          }
      }
  }
  updateGMenuHeader();
});

function updateGMenuHeader()
{
  gMenu.header = '<b>Group By:</b> ' + gMenu.text;
}


// filter for flexGrid
// create grid, some data
var grid = new wijmo.grid.FlexGrid('#fFlexGrid'),
  cv = new wijmo.collections.CollectionView(appData.getData(100)),
  filterEl = document.getElementById('fFilter'),
  filterText = '';

grid.itemsSource = cv;

filterEl.addEventListener('input',function(){
  filterText = this.value.toLowerCase();
  cv.refresh();
});

cv.filter = function(item){
  return !filterText || item.country.toLowerCase().indexOf(filterText) > -1;
}


// pagination for flexGrid
// create a CollectionView ,set the page size to 10, initialize pager.

var cv = new wijmo.collections.CollectionView(appData.getData(100)),
  pageButtons = Array.prototype.slice.call(document.querySelectorAll('#pPager button'));

cv.pageSize = 10;
updatePager();

var grid = new wijmo.grid.FlexGrid('#pFlexGrid');
grid.itemsSource = cv;

pageButtons.forEach(function(el){
  el.addEventListener('click',function(){
      updatePager(this.getAttribute('data-action'));
  });
});


function updatePager(action){
  var display = document.getElementById('pn'),
      fb = document.getElementById('pfb'),
      sb = document.getElementById('psb'),
      sf = document.getElementById('psf'),
      ff = document.getElementById('pff'),
      enableBackwards = false,
      enableForwards = false;

  switch (action){
      case 'fast-backward':
          cv.moveToFirstPage();
          break;
      case 'step-backward':
          cv.moveToPreviousPage();
          break;
      case 'step-forward':
          cv.moveToNextPage();
          break;
      case 'fast-forward':
          cv.moveToLastPage();
          break;
  }

  // update the pager text
  display.innerHTML = (cv.pageIndex+1)+'/'+(cv.pageCount);

  // determine which pager buttons to enable/disable
  enableBackwards = cv.pageIndex <= 0;
  enableForwards = cv.pageIndex >= cv.pageCount - 1;

  // enable / disable pager buttons
  fb.disabled = enableBackwards;
  sb.disabled = enableBackwards;
  sf.disabled = enableForwards;
  ff.disabled = enableForwards;
}
/*
// use initialize to setup flex's property.
var grid = new wijmo.grid.FlexGrid('#id');
grid.initialize({
  id:'',
  isReadOnly:true,
  autoGenerateColumns:false,
  allowSorting:false,
  //itemsSource:cv,
  bind:{
      bind:'url',
      update:'url',
      disableServerRead:false
  },
  selectionMode:wijmo.grid.selectionMode.ListBox,
  allowResizing:wijmo.grid.allowResizing.None,
  childItemsPath:'Children',
  cssClass:'grid',
  columns:[
      {
          binding:'ID',
          header:'ID',
          width:'*',
          align:'center'
      },
  ]
});
*/
var CustomGridEditor = (function () {
  /**
   * Initializes a new instance of a CustomGridEditor.
   */
  function CustomGridEditor(flex, binding, edtClass, options) {
      var _this = this;
      // save references
      this._grid = flex;
      this._col = flex.columns.getColumn(binding);
      // create editor
      this._ctl = new edtClass(document.createElement('div'), options);
      // connect grid events
      this._grid.beginningEdit.addHandler(this._beginningEdit, this);
      this._grid.scrollPositionChanged.addHandler(this._closeEditor, this);
      // connect editor events
      this._ctl.addEventListener(this._ctl.hostElement, 'keydown', function (e) {
          switch (e.keyCode) {
              case wijmo.Key.Tab:
              case wijmo.Key.Enter:
                  _this._closeEditor(true);
                  _this._grid.focus();
                  // forward event to the grid so it will move the selection
                  var evt = document.createEvent('HTMLEvents');
                  evt.initEvent('keydown', true, true);
                  evt['ctrlKey'] = e.ctrlKey;
                  evt['shiftKey'] = e.shiftKey;
                  evt['keyCode'] = e.keyCode;
                  _this._grid.hostElement.dispatchEvent(evt);
                  break;
              case wijmo.Key.Escape:
                  _this._closeEditor(false);
                  _this._grid.focus();
                  break;
          }
      });
      this._ctl.lostFocus.addHandler(function () {
          setTimeout(function () {
              if (!_this._ctl.containsFocus()) {
                  _this._closeEditor(true);
              }
          });
      });
      // open drop-down on f4/alt-down
      this._grid.addEventListener(this._grid.hostElement, 'keydown', function (e) {
          _this._openDropDown = false;
          if (e.keyCode == wijmo.Key.F4 ||
              (e.altKey && (e.keyCode == wijmo.Key.Down || e.keyCode == wijmo.Key.Up))) {
              _this._openDropDown = true;
              _this._grid.startEditing(true);
              e.preventDefault();
          }
      }, true);
      // close editor when user resizes the window
      window.addEventListener('resize', function () {
          if (_this._ctl.containsFocus()) {
              _this._closeEditor(true);
              _this._grid.focus();
          }
      });
  }
  Object.defineProperty(CustomGridEditor.prototype, "control", {
      // gets an instance of the control being hosted by this grid editor
      get: function () {
          return this._ctl;
      },
      enumerable: true,
      configurable: true
  });
  // handle the grid's beginningEdit event by canceling the built-in editor,
  // initializing the custom editor and giving it the focus.
  CustomGridEditor.prototype._beginningEdit = function (grid, args) {
      var _this = this;
      // check that this is our column
      if (grid.columns[args.col] != this._col) {
          return;
      }
      // check that this is not the Delete key
      // (which is used to clear cells and should not be messed with)
      var evt = args.data;
      if (evt && evt.keyCode == wijmo.Key.Delete) {
          return;
      }
      // cancel built-in editor
      args.cancel = true;
      // save cell being edited
      this._rng = args.range;
      // initialize editor host
      var rc = grid.getCellBoundingRect(args.row, args.col);
      wijmo.setCss(this._ctl.hostElement, {
          position: 'absolute',
          left: rc.left - 1 + pageXOffset,
          top: rc.top - 1 + pageYOffset,
          width: rc.width + 1,
          height: grid.rows[args.row].renderHeight + 1,
          borderRadius: '0px'
      });
      // initialize editor content
      if (!wijmo.isUndefined(this._ctl['text'])) {
          this._ctl['text'] = grid.getCellData(this._rng.row, this._rng.col, true);
      }
      else {
          throw 'Can\'t set editor value/text...';
      }
      // start editing item
      var ecv = wijmo.tryCast(grid.collectionView, 'IEditableCollectionView'), item = grid.rows[args.row].dataItem;
      if (ecv && item) {
          setTimeout(function () {
              ecv.editItem(item);
          }, 210); // FlexGrid commits edits 200ms after losing focus
      }
      // activate editor
      document.body.appendChild(this._ctl.hostElement);
      this._ctl.focus();
      setTimeout(function () {
          // get the key that triggered the editor
          var key = (evt && evt.charCode > 32)
              ? String.fromCharCode(evt.charCode)
              : null;
          // send key to editor
          if (key) {
              var input = _this._ctl.hostElement.querySelector('input');
              if (input instanceof HTMLInputElement) {
                  input.value = key;
                  wijmo.setSelectionRange(input, key.length, key.length);
                  var evtInput = document.createEvent('HTMLEvents');
                  evtInput.initEvent('input', true, false);
                  input.dispatchEvent(evtInput);
              }
          }
          else {
              _this._ctl.focus();
          }
          // open drop-down on F4/alt-down
          if (_this._openDropDown && _this._ctl instanceof wijmo.input.DropDown) {
              _this._ctl.isDroppedDown = true;
          }
      }, 50);
  };
  // close the custom editor, optionally saving the edits back to the grid
  CustomGridEditor.prototype._closeEditor = function (saveEdits) {
      if (this._rng) {
          var grid = this._grid, ctl = this._ctl, host = ctl.hostElement;
          // raise grid's cellEditEnding event
          var e = new wijmo.grid.CellEditEndingEventArgs(grid.cells, this._rng);
          grid.onCellEditEnding(e);
          // save editor value into grid
          if (saveEdits) {
              if (!wijmo.isUndefined(ctl['value'])) {
                  this._grid.setCellData(this._rng.row, this._rng.col, ctl['value']);
              }
              else if (!wijmo.isUndefined(ctl['text'])) {
                  this._grid.setCellData(this._rng.row, this._rng.col, ctl['text']);
              }
              else {
                  throw 'Can\'t get editor value/text...';
              }
              this._grid.invalidate();
          }
          // close editor and remove it from the DOM
          if (ctl instanceof wijmo.input.DropDown) {
              ctl.isDroppedDown = false;
          }
          host.parentElement.removeChild(host);
          this._rng = null;
          // raise grid's cellEditEnded event
          grid.onCellEditEnded(e);
      }
  };
  return CustomGridEditor;
}());
// new CustomGridEditor(grid,'date',wijmo.inputDate,{
//    format:'dd-MMM-yyyy'
// })